#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=${pkg}
mkdir -p build || exit 1
cd build || exit 1

extra_args=()
if [ -n "${feature_introspection}" ]; then
    extra_args+=(-Dintrospection=enabled)
fi
if [ -n "${feature_man}" ]; then
    extra_args+=(-Dman-pages=enabled)
fi

if [ "${arch}" != "${host_arch}" ]; then
    extra_args+=(--cross-file=/etc/crossfile.txt)

    # Use host python module for cross-compilation
    rm /usr/lib/gobject-introspection/giscanner/_giscanner.*.so
    cp -P /host/usr/lib/gobject-introspection/giscanner/_giscanner.*.so /usr/lib/gobject-introspection/giscanner/

    if [ -n "${feature_cross}" ]; then
        extra_args+=(-Dgi_cross_binary_wrapper="qemu-wrapper")
        extra_args+=(-Dgi_cross_ldd_wrapper=${triple}-ldd)

        # TODO: make this wrapper as a package
        cat > /usr/bin/qemu-wrapper <<EOF
#!/usr/bin/env bash
qemu-${arch} -E LD_LIBRARY_PATH=/usr/lib:/usr/lib64 \$@
EOF
        chmod +x /usr/bin/qemu-wrapper
    fi
fi

meson setup \
    --prefix=/usr ../${srcdir} \
    --libdir=lib \
    ${extra_args[@]} \
    || exit 1

if [ -n "${feature_cross}" ]; then
    # FIXME: how to make typelibs depends on gi-compile-repository wrapper?
    ninja -j ${MAX_JOBS} girepository/compiler/gi-compile-repository || exit 1
fi

ninja -j ${MAX_JOBS}
